
var $container = $('#container');
var $level1Menu = $('#level1-menu');

function createLevel2(menuInfo) {
    var $div = $('<div class="item-wrap">\
                            <div class="degree1">\
                                <div class="check-wrap2">\
                                    <span id="{0}" class="span-normal" parent="{1}" level="1_2"></span>\
                                    <label class="fw-b">{2}</label>\
                                </div>\
                                <div class="slide-btn3 active">展开</div>\
                            </div>\
                            <div class="degree2" style="display: none;">\
                                <table width="100%" border="0" cellspacing="0" cellpadding="0">\
                                </table>\
                            </div>\
                      </div>'.format(menuInfo.id, menuInfo.funcId, menuInfo.name));

    var $table = $div.find('table');

    $.each(menuInfo.child, function (i2, level2Info) {

        if (level2Info.child && level2Info.child[0].type !== '2') {

            var $tr = $('<tr>\
                                    <td width="148" class="bg-fbfcfd">\
                                        <div class="check-wrap2 mt0">\
                                            <span id="{0}" class="span-normal" data-haschild="true" level="2" parent="{1}"></span>\
                                            <label>{2}</label>\
                                        </div>\
                                   </td>\
                                   <td>\
                                        <div class="degree3">\
                                        </div>\
                                   </td>\
                                </tr>'.format(level2Info.id, level2Info.funcId, level2Info.name));

            var $degree3 = $tr.find('.degree3');
            $.each(level2Info.child, function (i3, level3Info) {

                var $dropDown = $('<div class="check-wrap2 dropdown-menu" style="height: 26px;">\
                                                <span id="{0}" class="span-normal"  level="3"  parent="{1}"></span>\
                                                <label>{2}</label>\
                            </div>'.format(level3Info.id, level3Info.funcId, level3Info.name)).appendTo($degree3);
                if (level3Info.child) {
                    //$dropDown.css('z-index', 11);
                    var $ul = $('<ul style="display: none;"></ul>').appendTo($dropDown);
                    $.each(level3Info.child, function (i6, buttonInfo) {
                        $ul.append('<li>\
                                            <div class="check-wrap2">\
                                                <span id="{0}" class="span-normal" level="4"></span>\
                                                <label class="dropdown-label">{1}</label>\
                                            </div>\
                            </li>'.format(buttonInfo.id, buttonInfo.name));
                    });
                }
            });
            $tr.appendTo($table);

        } else {//无五级菜单
            var $menu2 = $('<tr>\
                                        <td width="148" class="bg-fbfcfd">\
                                            <div class="degree3">\
                                                <div class="check-wrap2 dropdown-menu" style="height: 26px;">\
                                                    <span id="{0}" class="span-normal" level="3" parent="{1}"></span>\
                                                    <label>{2}</label>\
                                                </div>\
                                            </div>\
                                       </td>\
                                       <td>\
                                       </td>\
                                    </tr>'.format(level2Info.id, level2Info.funcId, level2Info.name)).appendTo($table);
            if (level2Info.child) {
                var $dropDown = $menu2.find('.dropdown-menu');
                var $ul = $('<ul style="display: none;"></ul>').appendTo($dropDown);
                $.each(level2Info.child, function (i6, buttonInfo) {
                    $ul.append('<li>\
                                            <div class="check-wrap2">\
                                                <span id="{0}" class="span-normal" level="4"></span>\
                                                <label>{1}</label>\
                                            </div>\
                            </li>'.format(buttonInfo.id, buttonInfo.name));
                });
            }
        }
    });


    $div.appendTo($container);

}
var wholeCheckCss = 'span-all',
    halfCheckCss = 'span-some',
    normalCheckCss = 'span-normal';
$container.on('click.slide', '.slide-btn3', function () {//收起、展开

    var _$t = $(this),
        $parent = _$t.closest('.item-wrap'),
        $degree2 = $parent.find('.degree2');
    var isActive = _$t.hasClass('active');

    $parent[isActive ? 'addClass' : 'removeClass']('active');
    $degree2[isActive ? 'show' : 'hide']();
    _$t.html(isActive ? '收起' : '展开');

    _$t.toggleClass('active');
}).on('mouseenter.show', '.dropdown-menu', function () {
    $(this).find('>ul').show().css('z-index', '10');
}).on('mouseleave.hide', '.dropdown-menu', function () {
    $(this).find('>ul').hide().css('z-index', 'inherit');
}).on('click.check', '.check-wrap2 span', function () {

    var _$t = $(this);
    var $grandpa = _$t.parent().parent();//爷爷节点

    var isChecked = _$t.hasClass('span-all');

    if ($grandpa.hasClass('degree1')) {//最顶级菜单

        if (isChecked) {
            $grandpa.next().find('span').attr('class', normalCheckCss);
            _$t.attr('class', normalCheckCss);
        } else {
            $grandpa.next().find('span').attr('class', wholeCheckCss);
            _$t.attr('class', wholeCheckCss);
        }

    } else if ($grandpa.attr('id') === 'level1-menu') {//首页等菜单
        $(this).toggleClass('span-all');
    } else {

        var level = $(this).attr('level');
        if (level == '2') {
            _$t.closest('tr').find('span').attr('class', isChecked ? normalCheckCss : wholeCheckCss);
            checkLevel1(_$t);
        } else if (level == '3') {
            // if (isChecked) {//取消选择菜单，下面所有的按钮权限都取消
            //     _$t.parent().find('span').attr('class', isChecked ? normalCheckCss : wholeCheckCss);
            // } else {//选择菜单，下面所有的按钮权限不受影响
            //     console.info(_$t);
            // }
            _$t.parent().find('span').attr('class', isChecked ? normalCheckCss : wholeCheckCss);
            checkLevel2(_$t);
        } else if (level == '4') {
            _$t.attr('class', isChecked ? normalCheckCss : wholeCheckCss);
            checkeLevel3(_$t);
        }

    }
}).on('click.labelClick', 'label', function () {//点击label触发边上的span的click.check事件
    var prev = $(this).siblings('span');
    if (prev.length) {
        prev.trigger('click.check');
    }
}).on('dblclick', '.degree1', function(){
    var _$t = $(this),
        $parent = _$t.find('.slide-btn3').closest('.item-wrap'),
        $degree2 = $parent.find('.degree2');
    var isActive = _$t.find('.slide-btn3').hasClass('active');
    $parent[isActive ? 'addClass' : 'removeClass']('active');
    $degree2[isActive ? 'show' : 'hide']();
    _$t.find('.slide-btn3').html(isActive ? '收起' : '展开');
    _$t.find('.slide-btn3').toggleClass('active');
});

/**
 * 增加全部收起和全部展开功能
 */
$("#showAll").on('click', function(){
    var _$t = $(this);
    var isActive = _$t.hasClass('active');
    var $parent = $(".slide-btn3").closest('.item-wrap'),
        $degree2 = $parent.find('.degree2');
    $parent[isActive ?    'removeClass' : 'addClass']('active');
    $degree2[isActive ?  'hide' : 'show']();
    $(".slide-btn3").html(isActive ?  '展开' : '收起');
    $(".slide-btn3")[isActive ?    'addClass' : 'removeClass']('active');

    isActive ? _$t.removeClass('active') : _$t.addClass('active');
    _$t[isActive ? 'removeClass' : 'addClass']('active');
    _$t.html(isActive ?  '展开全部' : '收起全部');

});




function checkLevel1($span) {
    var $degree2 = $span.closest('.degree2'),
        $level1Span = $degree2.siblings('.degree1').find('span');
    var $span = $degree2.find('span');
    if ($span.filter('.' + wholeCheckCss).length == $span.length) {
        $level1Span.attr('class', wholeCheckCss);
    } else if ($span.filter('.' + normalCheckCss).length == $span.length) {
        $level1Span.attr('class', normalCheckCss);
    } else {
        $level1Span.attr('class', halfCheckCss);
    }
}

function checkLevel2($span) {
    var $td = $span.closest('td'),
        $level2Span = $td.prev().find('span');
    if (!$level2Span.length) {//说明该菜单下面没有五级菜单
        checkLevel1($span);
        return;
    }
    var $span = $td.find('span');
    if ($span.filter('.' + wholeCheckCss).length == $span.length) {
        $level2Span.attr('class', wholeCheckCss);
    } else if ($span.filter('.' + normalCheckCss).length == $span.length) {
        $level2Span.attr('class', normalCheckCss);
    } else {
        $level2Span.attr('class', halfCheckCss);
    }
    checkLevel1($span);
}

function checkeLevel3($span) {
    var $td = $span.closest('ul'),
        $level3Span = $td.siblings('span');
    var $span = $td.find('span');
    //if ($span.filter('.' + wholeCheckCss).length == $span.length) {
    //    $level3Span.attr('class', wholeCheckCss);
    //} else if ($span.filter('.' + normalCheckCss).length == $span.length) {
    //    $level3Span.attr('class', normalCheckCss);
    //} else {
    //    $level3Span.attr('class', halfCheckCss);
    //}
    if ($span.filter('.' + normalCheckCss).length == $span.length) {
        $level3Span.attr('class', normalCheckCss);
    } else if($span.filter('.' + normalCheckCss).length != 0 && $span.filter('.' + normalCheckCss).length < $span.length){
        $level3Span.attr('class', halfCheckCss);
    } else {
        $level3Span.attr('class', wholeCheckCss);
    }
    if ($level3Span.closest('td').attr('colspan') == 2) {//说明父菜单是四级菜单
        checkLevel1($span);
    } else {
        checkLevel2($span);
    }
}



var tableTree = {
    getData: function () {
        var $span = $container.find('span.' + halfCheckCss + ', span.' + wholeCheckCss);
        var data = {
            funcIds: [],
            buttonIds: []
        };
        $.each($span, function (i, span) {
            var _$t = $(span),
                level = _$t.attr('level');
            if (level == '4') {
                data.buttonIds.push(_$t.attr('id'));
            } else if (level == '3' || level == '1') {
                if(level == '3'){
                    data.funcIds.push(_$t.attr('parent'));
                }
                data.funcIds.push(_$t.attr('id'));
            } else if(level == '2' || level == '1_2'){
                data.funcIds.push(_$t.attr('id'));
                data.funcIds.push(_$t.attr('parent'));
            }
        });
        return data;
    },
    init: function (data) {
        $level1Menu.empty();
        $container.find('>div:gt(0)').remove();
        $container.append('<div class="item-wrap">\
            <div class="degree1">\
            <div id="level1-menu">\
            <div class="check-wrap2" id="mainAllDiv" >\
            <span id="allMain" level="0" onclick="checkMain()"></span>\
            <label class="fw-b">首页</label>\
            </div>\
            </div>\
            </div>\
            <div class="degree1" id="firstTab">\
            </div>\
            </div>');

        var lv1Tab = "";
        $.each(data, function (i, item) {
            if (item.child) {
                $.each(item.child, function (i2, item2) {
                    createLevel2(item2);
                });
            } else {
                lv1Tab += '<div class="check-wrap2 dropdown-menu" ><span id="{0}" level="1" onclick="checkLevel1Main(this)"></span><label class="fw-b">{1}</label></div>'.format(item.id, item.name)
            }
        });
        var str= '<tr><td id="mainTd">'+lv1Tab+'</td></tr>';
        $("#firstTab").html(str);

    },
    setData: function (data) {
        $.each(data, function (i, item) {
            $('#' + item.id).attr('class', wholeCheckCss);
        });
        if (data.length) {
            $.each($container.find('>.item-wrap:gt(0)'), function (i, div) {
                var $tr = $('table tr', div);
                $.each($tr, function (i2, tr) {

                    var $dropdown = $('.dropdown-menu', tr);

                    if ($('.' + wholeCheckCss, $dropdown).length) {//每行中至少有一个span被选中
                        var $firstSpan = $dropdown.last().find('span:first');
                        $firstSpan.attr('class', $firstSpan.hasClass(wholeCheckCss) ? normalCheckCss : wholeCheckCss);
                        $firstSpan.trigger('click.check');
                    }

                    //$.each($span, function (i3, _span) {
                    //    $(_span).attr('class', normalCheckCss).trigger('click.check');
                    //});

                    if (i2 === $tr.length - 1) {
                        checkLevel2($('span:eq(0)', tr));
                    }
                });
            })
            checkParentMain();
        }
    }
}

function checkMain(){
    var $g = $("#mainAllDiv").parent().parent();
    var isActive = $("#mainAllDiv").find("span").removeClass("span-some").hasClass("span-all");
    var span = $g.next().find("span");
    if(!isActive){
        $(span).removeClass().addClass("span-all");
    }else{
        $(span).removeClass().addClass("span-normal");
    }
}

function checkLevel1Main(obj){
    var isActive = $(obj).hasClass("span-all");
    if(isActive){
        $(obj).removeClass();
    }else{
        $(obj).removeClass().addClass("span-all");
    }
    checkParentMain();
}

function checkParentMain(){
    var isActive = true;
    var isActiveAll = $("#firstTab").find("span").hasClass("span-all");
    $.each($("#firstTab").find("span"), function(i, item) {
        var hasClass = $(item).prop("class");
        if(hasClass == ''){
            isActive = false;
        }
    });
    if(isActive && isActiveAll){
        $("#mainAllDiv").find("span").removeClass().addClass("span-all");
    }else if(!isActive && isActiveAll){
        $("#mainAllDiv").find("span").removeClass().addClass("span-some");
    }else{
        $("#mainAllDiv").find("span").removeClass().addClass("span-normal");
    }
}